package br.cin.stadium.middleware.network;

import br.cin.stadium.middleware.marshall.MarshallInputStream;

/**
 * @author Jorge, Fabiano, Rafael, Vando
 * 
 */
public class DataInputStream implements MarshallInputStream {

	private byte[] data;
	private int index;
	
	private BufferStream stream;

	/**
	 * @param initialSize
	 * @param incrementalValue
	 */
	public DataInputStream(byte[] data) {
		this.data = data;
	}

	public DataInputStream(BufferStream stream) {
		this.stream = stream;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see br.cin.stadium.middleware.marshall.MarshallInputStream#readUTF()
	 */
	public String readUTF() {
		String value = null;

		int stringSize = this.readInt();
		byte[] sData = new byte[stringSize];

		for (int i = 0; i < stringSize; i++) {
			sData[i] = this.readByte(); 
		}
		
		value = new String(sData);
		return value;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see br.cin.stadium.middleware.marshall.MarshallInputStream#readInt()
	 */
	public int readInt() {
		int b0 = this.readByte() & 0xFF;
		int b1 = (this.readByte() << 8) & 0xFF00;
		int b2 = (this.readByte() << 16) & 0xFF0000;
		int b3 = (this.readByte() << 24) & 0xFF000000;

		int value = (b3 | b2) | (b1 | b0);

		return value;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * br.cin.stadium.middleware.marshall.MarshallInputStream#readBytes(int)
	 */
	public byte[] readBytes(int size) {
		byte[] dataTemp = new byte[size];
		
		if(this.stream != null) {
			dataTemp = this.stream.readBytes(size);
		} else {
			System.arraycopy(this.data, index, dataTemp, 0, size);
			this.index += size;
		}


		return dataTemp;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see br.cin.stadium.middleware.marshall.MarshallInputStream#readByte()
	 */
	public byte readByte() {
		byte b = -1;
		
		if(this.stream != null) {
			b = (byte)this.stream.readByte();
		} else {
			b = this.data[index++];
		}
		
		return b;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see br.cin.stadium.middleware.marshall.MarshallInputStream#getData()
	 */
	public byte[] getData() {
		return this.data;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see br.cin.stadium.middleware.marshall.MarshallInputStream#available()
	 */
	public int available() {
		return this.data.length - index;
	}
}
